const app = getApp()
var template = require('../../template/template.js');
var request = require('../../utils/https.js');
var uri = 'cart/index.html';
var modify = 'cart/modify_cart.html';
var del = 'cart/cart_del.html';
var modstatus = 'cart/status.html';
var allstatus = 'cart/all_status.html';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    carts: [],               // 购物车列表
    hasList: false,          // 列表是否有数据
    totalPrice: 0,           // 总价，初始为0
    totalCount: 0,           // 数量，初始为0
    selectAllStatus: 1,    // 全选状态，默认全选
    obj: {
      name: "成功"
    }
  },
  /**
   * 下单
   */
   order:function(){
     if (this.data.totalCount<=0){
       wx.showToast({
         title: '请选择需要结算的产品',
         icon: 'none',
       })
     }else{
       wx.navigateTo({
         url: '../comfirm/comfirm',
       })
     }
   },
  /**
   * 当前商品选中事件
   */
  selectList(e) {
    var that=this;
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    const status = carts[index].status;
    request.req(modstatus, {
      user_id: wx.getStorageSync('userId'),
      cart_id: carts[index].id
    }, (err, res) => {
      if (res.data) {
        if(status){
          carts[index].status = 2;
        }else{
          carts[index].status = 1;
        }
        that.setData({
          carts: carts
        });
        that.isAllstatus();
        that.getTotalPrice();
      }
    })
  },
  isAllstatus:function(){
    let k=0,g=0;
    let carts = this.data.carts;
    for (let i = 0; i < carts.length; i++) {
      g++;
      if (carts[i].status == 2){
         k++;
      }
    }
    if(k==g){
      this.setData({
        selectAllStatus: 1,
      });
    }
    else{
      this.setData({
        selectAllStatus: 0,
      });
    }
  },
  /**
   * 删除购物车当前商品
   */
  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    var that = this;
    request.req(del, {
      user_id: wx.getStorageSync('userId'),
      cart_id: carts[index].id
    }, (err, res) => {
      if (res.data) {
        carts.splice(index, 1);
        this.setData({
          carts: carts
        });
        if (!carts.length) {
          this.setData({
            hasList: false
          });
        } else {
          this.getTotalPrice();
        }
      } else {
        wx.showToast({
          title: '删除失败',
          icon: 'none',
        })
      }
    })
  },

  /**
   * 购物车全选事件
   */
  selectAll(e) {
    let that=this;
    let selectAllStatus = this.data.selectAllStatus;
    let status=1;
    if (selectAllStatus)
     {status=1}
    else{status =2}
    let carts = this.data.carts;
    request.req(allstatus, {
      user_id: wx.getStorageSync('userId'),
      status: status
    }, (err, res) => {
      if (res.data) {
        for (let i = 0; i < carts.length; i++) {
          carts[i].status = status;
        }
        that.setData({
          carts: carts,
        })
        that.isAllstatus();
        that.getTotalPrice();
      }
    })
  },

  /**
   * 绑定加数量事件
   */
  addCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let num = carts[index].number;
    num = num + 1;
    this.modifyData(carts[index].id, num, index);
  },

  /**
   * 绑定减数量事件
   */
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    const obj = e.currentTarget.dataset.obj;
    let carts = this.data.carts;
    let num = carts[index].number;
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    this.modifyData(carts[index].id,num,index);
  },

  /**
   * 计算总价
   */
  getTotalPrice() {
    let carts = this.data.carts;                 // 获取购物车列表
    let count = 0;                               // 获取购物车产品数量
    let total = 0;
    for (let i = 0; i < carts.length; i++) {         // 循环列表得到每个数据
      if (carts[i].status==2) {                     // 判断选中才会计算价格
        total += carts[i].number * carts[i].unit_price;   // 所有价格加起来
        count++;                                  // 所有数量加起来
      }                       
    }
    this.setData({                                // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2),
      totalCount:count
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    template.tabbar("tabBar", 2, this)//0表示第一个tabbar
    wx.showNavigationBarLoading();
    setTimeout(function(){
      wx.hideNavigationBarLoading();
    },2000);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  getData: function () {
    var that = this;
    var list=[]
    request.req(uri, {
      user_id: wx.getStorageSync('userId')
    }, (err, res) => {
      if (res.data.cart_count>0){
          that.setData({
            hasList: true,
            carts: res.data.list
          })
          that.getTotalPrice();
          that.isAllstatus();
      }else{
        hasList: false
      }
    })
  },
  modifyData: function (cartId,num,index) {
    var that = this;
    let carts = that.data.carts;
    request.req(modify, {
      user_id: wx.getStorageSync('userId'),
      cart_id: cartId,
      number:num
    }, (err, res) => {
      if (res.data) {
        carts[index].number = num;
        that.setData({
          carts: carts
        });
        this.getTotalPrice();
      }
    })
  },
  onShow: function () {
    this.getData();
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  }
})